package cn.rengy.web.framework.antireptile.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.alibaba.fastjson.JSON;

import cn.rengy.lang.ResultEntity;
import cn.rengy.tool.web._WebUtils;
import cn.rengy.web.framework.antireptile.annotation.AntiReptile;
import cn.rengy.web.framework.antireptile.rule.RuleActuator;
import lombok.extern.slf4j.Slf4j;

/**
 * 反爬虫拦截器
 */
@Slf4j
public class AntiReptileInterceptor implements AsyncHandlerInterceptor {

	@Autowired(required=false)
	private RuleActuator ruleActuator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	//String requestUrl = request.getRequestURI();
        //log.debug("getRequestURI={}",requestUrl);
    	if(handler instanceof HandlerMethod) {
        	HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            AntiReptile antiReptile = AnnotationUtils.findAnnotation(method, AntiReptile.class);
            if (antiReptile != null&&!ruleActuator.isAllowed(request, response)) {
            	response.setCharacterEncoding(Consts.UTF_8.name());
    			response.setStatus(HttpStatus.FORBIDDEN.value());
    	        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    	        //response.addHeader("Redirect-URL", loginUrl);
    	        String str=JSON.toJSONString(ResultEntity.fail("拒绝访问,24小时后恢复"));
    	        _WebUtils.responseWrite(str, response);
                return false;
            }
        }
        return true;
    }

    
}
